/**
 * Created by zhang_renyang on 15/1/4.
 */
var dateUtils = require('../utils/dateUtils');
var replyModel = require('../schema/reply');
var Reply = function(reply) {
    this.content = reply.content;
    this.parent_id = reply.parent_id;
    this.article_id = reply.article_id;
    this.user_id = reply.user_id;
}

Reply.prototype.save = function(callback){
    var newReply = new replyModel( {
        content:this.content,
        parent_id:this.parent_id,
        article_id:this.article_id,
        crete_time:dateUtils.getTime(),
        user_id:this.user_id
    });
    newReply.save(function(err,reply){
        if(err)
            callback(err);
        callback(null,reply);
    });
}

Reply.findByTopicId = function(article_id,callback){
    replyModel.find({article_id:article_id},null,{},function(err,replies){
        if(err)
           callback(err);
        patchReplies(replies);
        callback(null,replies);
    });
}

function patchReplies(replies){
    if(replies && replies.length){
        for(var i=0;i<replies.length;i++){
            var reply = replies[i];
            replyModel.find({parent_id:reply._id},null,{},function(err,replies){
                patchReplies(replies);
                replies.children = replies;
            });
        }
    }
}


module.exports = Reply;

